package com.example.edianzu.somur.login.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.example.edianzu.somur.App;
import com.example.edianzu.somur.MainActivity;
import com.example.edianzu.somur.R;
import com.example.edianzu.somur.api.APIConstants;
import com.example.edianzu.somur.api.bean.LoginInfo;
import com.example.edianzu.somur.api.bean.ResetPassword;
import com.example.edianzu.somur.api.bean.VerificationCode;
import com.example.edianzu.somur.api.constans.AppContents;
import com.example.edianzu.somur.api.manager.APIManager;
import com.example.edianzu.somur.utils.content.StatusBarUtils;
import com.example.edianzu.somur.utils.content.ValidateUtils;
import com.example.edianzu.somur.utils.manager.ActivityManager;
import com.example.edianzu.somur.utils.view.BaseActivity;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public class FindPasswordActivity extends BaseActivity {

    @BindView(R.id.FindPasswordActivity_ImageView_back)
    AppCompatImageView FindPasswordActivityImageViewBack;
    @BindView(R.id.FindPasswordActivity_EditText_phoneNumber)
    AppCompatEditText FindPasswordActivityEditTextPhoneNumber;
    @BindView(R.id.FindPasswordActivity_Button_VerificationCode)
    AppCompatButton FindPasswordActivityButtonVerificationCode;
    @BindView(R.id.FindPasswordActivity_EditText_verificationCode)
    AppCompatEditText FindPasswordActivityEditTextVerificationCode;
    @BindView(R.id.FindPasswordActivity_EditText_passWord)
    AppCompatEditText FindPasswordActivityEditTextPassWord;
    @BindView(R.id.FindPasswordActivity_Button_openAccount)
    AppCompatButton FindPasswordActivityButtonOpenAccount;
    @BindView(R.id.FindPasswordActivity_TextView_info)
    AppCompatTextView FindPasswordActivityTextViewInfo;
    private int times=30;//定时60s短信验证
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_password);
        ButterKnife.bind(this);

        StatusBarUtils.setWindowStatusBarColor(this, R.color.title);
        sharedPreferences = App.getApp().getSharedPreferences();
    }

    @OnClick({R.id.FindPasswordActivity_ImageView_back, R.id.FindPasswordActivity_Button_VerificationCode, R.id.FindPasswordActivity_Button_openAccount})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.FindPasswordActivity_ImageView_back:

                finish();
                break;
            case R.id.FindPasswordActivity_Button_VerificationCode:

                String mobile = FindPasswordActivityEditTextPhoneNumber.getText().toString();
                final SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString("mobile_find",mobile);

                if (!TextUtils.isEmpty(mobile) && ValidateUtils.isMobileNO(mobile)) {

                    APIManager.getApiManagerInstance().getSMSVerificationCode(new Observer<VerificationCode>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull VerificationCode verificationCode) {

                            if (verificationCode.getStatus() == APIConstants.STATUS) {

                                String verificationCodeData = verificationCode.getData();
                                edit.putString("verificationCodeData_find", verificationCodeData).apply();
                                Toast.makeText(FindPasswordActivity.this, "验证码已发送", Toast.LENGTH_SHORT).show();
//                                FindPasswordActivityEditTextVerificationCode.setText(verificationCode.getData());

//                                开启倒计时，并且按钮不可点击
                                FindPasswordActivityButtonVerificationCode.post(new Runnable() {
                                    @Override
                                    public void run() {

                                        FindPasswordActivityButtonVerificationCode.setClickable(false);
                                        final Timer timer = new Timer();
                                        /*第一个参数"new MyTask(event.getServletContext())": 是 TimerTask 类，在包：import java.util.TimerTask .使用者要继承该类，并实现 public void run() 方法，因为 TimerTask 类实现了 Runnable 接口。
                                        第二个参数"0"的意思是:(0就表示无延迟) 当你调用该方法后，该方法必然会调用 TimerTask 类 TimerTask 类 中的 run() 方法，这个参数就是这两者之间的差值，转换成汉语的意思就是说，用户调用 schedule() 方法后，要等待这么长的时间才可以第一次执行 run() 方法。
                                        第三个参数"60*60*1000"的意思就是: (单位是毫秒60*60*1000为一小时) (单位是毫秒3*60*1000为三分钟) 第一次调用之后，从第二次开始每隔多长的时间调用一次 run() 方法*/
                                        timer.schedule(new TimerTask() {
                                            @Override
                                            public void run() {

                                                FindPasswordActivityButtonVerificationCode.post(new Runnable() {
                                                    @Override
                                                    public void run() {

                                                        FindPasswordActivityButtonVerificationCode.setText(times+" s");
                                                    }
                                                });

                                                times--;
                                                if (times<0){
//                                                    重置时间
                                                    times=30;
                                                    FindPasswordActivityButtonVerificationCode.post(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            FindPasswordActivityButtonVerificationCode.setClickable(true);
                                                            FindPasswordActivityButtonVerificationCode.setText("获取验证码");
                                                        }
                                                    });
                                                    timer.cancel();
                                                }
                                            }
                                        },1*1000,1*1000);
                                    }
                                });
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    }, mobile, APIConstants.COMPANY_ID);
                } else {

                    Toast.makeText(this, "手机号错误，请用户检查后输入！！！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.FindPasswordActivity_Button_openAccount:

                String mobile_editor = sharedPreferences.getString("mobile_find","");
                String verificationCodeData_editor = sharedPreferences.getString("verificationCodeData_find", "");
                final String password = FindPasswordActivityEditTextPassWord.getText().toString();
                final String mobile_Second=FindPasswordActivityEditTextPhoneNumber.getText().toString();
                String verificationCode = FindPasswordActivityEditTextVerificationCode.getText().toString();

                if (mobile_editor.equals(mobile_Second)&&ValidateUtils.isMobileNO(mobile_Second)  && !TextUtils.isEmpty(password) && verificationCode.equals(verificationCodeData_editor)) {

                    APIManager.getApiManagerInstance().setResetPassword(new Observer<ResetPassword>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull ResetPassword resetPassword) {

                            if (resetPassword.getStatus() == AppContents.STATUS) {

                                Toast.makeText(FindPasswordActivity.this, /*resetPassword.getMsg() + */"密码设置成功", Toast.LENGTH_SHORT).show();
//                                开启登录
                                APIManager.getApiManagerInstance().getLoginInfo(new Observer<LoginInfo>() {
                                    @Override
                                    public void onSubscribe(@NonNull Disposable d) {

                                    }

                                    @Override
                                    public void onNext(@NonNull LoginInfo loginInfo) {

//                        Log.d("onCreate", "onNext: "+loginInfo.getData().getCompany_id()+"```````````````"+loginInfo.getData().getMobile());

                                        if (loginInfo.getStatus() == 200) {

                                            SharedPreferences.Editor editor = sharedPreferences.edit();
                                            editor.putString("phone", mobile_Second);
                                            editor.putString("password", password);
                                            editor.putString("company_id", loginInfo.getData().getCompany_id()).apply();

                                            Intent intent = new Intent(FindPasswordActivity.this, MainActivity.class);
                                            intent.putExtra("member_id", loginInfo.getData().getMember_id());
                                            intent.putExtra("login", loginInfo);
                                            startActivity(intent);

//                                            销毁之前所有的Activity
                                            ActivityManager.finishAll();
                                        }
                                    }

                                    @Override
                                    public void onError(@NonNull Throwable e) {

                                        Toast.makeText(FindPasswordActivity.this, "登录信息有误，请确认后再次登录！！！", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                }, mobile_Second, password, APIConstants.COMPANY_ID);


                            }else {

                                FindPasswordActivityTextViewInfo.setVisibility(View.VISIBLE);
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    }, mobile_editor, APIConstants.COMPANY_ID, password);
                } else {

                    if (!TextUtils.isEmpty(password) && !TextUtils.isEmpty(verificationCode)) {

                        if (verificationCode.equals(verificationCodeData_editor)) {

                            Toast.makeText(this, "手机号错误，请用户检查后输入！！！", Toast.LENGTH_SHORT).show();
                        } else {

                            Toast.makeText(this, "验证码有误，请用户检查后请重新输入！！！", Toast.LENGTH_SHORT).show();
                        }
                    } else {

                        Toast.makeText(this, "验证码或手机号为空，请用户检查后重新输入！！！", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }
}
